﻿using Microsoft.AspNetCore.Mvc.Filters;

namespace BlogSystem.Exception.Filter;

public class GlobalExceptionFilter : IExceptionFilter
{
    public void OnException(ExceptionContext context)
    {
        var exception = context.Exception;
        if (exception is ValidatorException validatorException)
        {
            context.HttpContext.Response.StatusCode = 401;
            context.HttpContext.Response.WriteAsJsonAsync(new
            {
                message = string.Join(";", validatorException.ValidationFailures.Select(e => e.ErrorMessage))
            });
        }
        else if (exception is BusinessException businessException)
        {
            context.HttpContext.Response.StatusCode = 401;
            context.HttpContext.Response.WriteAsJsonAsync(new
            {
                message=businessException.Message
            });
        }
    }
}